﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Baidu.Aip.Ocr;
using Newtonsoft.Json.Linq;

namespace Baidu.Aip.Demo
{
    internal class OcrDemo
    {
        public static string ak = "FgeNKtnM927MtDCtAtbeBOqG";
        public static string sk = "hpqgl6iqS4Hk8eBNdGzgWFAGIz9NcBEA";
        public static Ocr.Ocr client = new Ocr.Ocr(ak, sk);
        public static Form form = new Form(ak, sk);

        /// <summary>
        /// 通用文字识别
        /// </summary>
        /// <param name="imgPath">图片路径(本地图片或网络图片)</param>
        /// <param name="isLocal">是否为本地图片，true：本地图片，false：网络图片</param>
        /// <returns></returns>
        public static string GeneralBasic(string imgPath,bool isLocal)
        {
            StringBuilder sb=new StringBuilder();
            var result = new JObject();

            try
            {
                if (isLocal)
                {
                    var image = File.ReadAllBytes(imgPath);
                    result = client.GeneralBasic(image);
                }
                else
                {
                    result = client.GeneralBasic(imgPath);
                }
                JToken jtoken = result["words_result"];
                foreach (JObject jp in jtoken)
                {
                    sb.Append(jp["words"].ToString());
                }
            }
            catch
            {
                sb.Clear();
                sb.Append("程序异常");
            }
            return sb.ToString();
        }

        /// <summary>
        /// 文字识别 高精度识别
        /// </summary>
        /// <param name="imgPath"></param>
        /// <returns></returns>
        public static string Accurate(string imgPath)
        {
            StringBuilder sb = new StringBuilder();
            try
            {
                var image = File.ReadAllBytes(imgPath);
                var result = client.Accurate(image);
                JToken jtoken = result["words_result"];
                foreach (JObject jp in jtoken)
                {
                    sb.Append(jp["words"].ToString());
                }
            }
            catch
            {
                sb.Clear();
                sb.Append("程序异常");
            }
            return sb.ToString();
        }

        /// <summary>
        /// 文字识别 带生僻字版
        /// </summary>
        /// <param name="imgPath"></param>
        /// <returns></returns>
        public static string GeneralEnhanced(string imgPath)
        {
            StringBuilder sb=new StringBuilder();
            try
            {
                var image = File.ReadAllBytes(imgPath);
                var result = client.GeneralEnhanced(image);
                JToken jtoken = result["words_result"];
                foreach (JObject jp in jtoken)
                {
                    sb.Append(jp["words"].ToString());
                }
            }
            catch
            {
                sb.Clear();
                sb.Append("程序异常");
            }
            return sb.ToString();
        }

        /// <summary>
        /// 文字识别 带位置版本(文字在图片中的位置)
        /// </summary>
        /// <param name="imgPath"></param>
        /// <returns></returns>
        public static string GeneralWithLocatin(string imgPath)
        {
            StringBuilder sb=new StringBuilder();
            try
            {
                var image = File.ReadAllBytes(imgPath);
                var result = client.GeneralWithLocatin(image, null);
                JToken jtoken = result["words_result"];
                foreach (JObject jp in jtoken)
                {
                    sb.Append(jp["words"].ToString());
                }
            }
            catch
            {
                sb.Clear();
                sb.Append("程序异常");
            }
            return sb.ToString();
        }

        /// <summary>
        /// 网图识别
        /// </summary>
        /// <param name="imgPath"></param>
        /// <returns></returns>
        public static string WebImage(string imgPath)
        {
            StringBuilder sb=new StringBuilder();
            try
            {
                var image = File.ReadAllBytes(imgPath);
                var result = client.WebImage(image, null);
                JToken jtoken = result["words_result"];
                foreach (JObject jp in jtoken)
                {
                    sb.Append(jp["words"].ToString());
                }
            }
            catch
            {
                sb.Clear();
                sb.Append("程序异常");
            }
            return sb.ToString();
        }

 

        /// <summary>
        /// 文字识别 高精度识别(带位置信息)
        /// </summary>
        /// <param name="imgPath"></param>
        /// <returns></returns>
        public static string AccurateWithLocation(string imgPath)
        {
            StringBuilder sb=new StringBuilder();
            try
            {
                var image = File.ReadAllBytes(imgPath);
                var result = client.AccurateWithLocation(image);
                JToken jtoken = result["words_result"];
                foreach (JObject jp in jtoken)
                {
                    sb.Append(jp["words"].ToString());
                }
            }
            catch
            {
                sb.Clear();
                sb.Append("程序异常");
            }
            return sb.ToString();
        }

        /// <summary>
        /// 银行卡识别
        /// </summary>
        /// <param name="imgPath"></param>
        /// <returns></returns>
        public static string BankCard(string imgPath)
        {
            StringBuilder sb=new StringBuilder();
            var image = File.ReadAllBytes(imgPath);
            var result = client.BankCard(image);
            JToken jk= result["result"];
            string bank_card_number = jk["bank_card_number"].ToString();
            string bank_card_type = jk["bank_card_type"].ToString();
            string bank_name = jk["bank_name"].ToString();
            sb.Append(bank_name + "_" + bank_card_number + "_" + bank_card_type);
            return sb.ToString();
        }

        /// <summary>
        /// 身份证识别
        /// </summary>
        /// <param name="idCardFront">身份证正面</param>
        /// <param name="idCardOpposite">身份证反面</param>
        /// <returns></returns>
        public static string Idcard(string idCardFront,string idCardOpposite)
        {
            StringBuilder sb=new StringBuilder();
            byte[] image = null;
            JObject result = new JObject();
            if (idCardFront != null)
            {
                image = File.ReadAllBytes(idCardFront);
                var options = new Dictionary<string, object>
                {
                    {"detect_direction", "true"} // 检测方向
                };
                // 身份证正面识别
                result = client.IdCardFront(image, options);
                JToken jk = result["words_result"];
                string name = jk["姓名"]["words"].ToString();
                string sex = jk["性别"]["words"].ToString();
                string nation = jk["民族"]["words"].ToString();
                string birthday = jk["出生"]["words"].ToString();
                string address = jk["住址"]["words"].ToString();
                string idcard = jk["公民身份号码"]["words"].ToString();
                sb.Append(name+"_"+sex+"_"+nation+"_"+birthday+"_"+address+"_"+idcard);
            }

            if (idCardOpposite != null)
            {
                // 身份证背面识别
                image = File.ReadAllBytes(idCardOpposite);
                result = client.IdCardBack(image);
                JToken jk = result["words_result"];
                string signName = jk["签发机关"]["words"].ToString();
                string start = jk["签发日期"]["words"].ToString();
                string end = jk["失效日期"]["words"].ToString();
                sb.Append("_"+signName+"_"+start+"_"+end);
            }
            return sb.ToString();
        }

        /// <summary>
        /// 驾驶证识别
        /// </summary>
        /// <param name="imgPath"></param>
        /// <returns></returns>
        public static string DrivingLicense(string imgPath)
        {
            StringBuilder sb=new StringBuilder();
            try
            {
                var image = File.ReadAllBytes(imgPath);
                var result = client.DrivingLicense(image);
                JToken jk = result["words_result"];
                string id = jk["证号"]["words"].ToString();
                string usefulLife = jk["有效期限"]["words"].ToString();
                string quasiCarType = jk["准驾车型"]["words"].ToString();
                string startTime = jk["有效起始日期"]["words"].ToString();
                string address = jk["住址"]["words"].ToString();
                string name = jk["姓名"]["words"].ToString();
                string country = jk["国籍"]["words"].ToString();
                string birthday = jk["出生日期"]["words"].ToString();
                string sex = jk["性别"]["words"].ToString();
                string firstTime = jk["初次领证日期"]["words"].ToString();
                sb.Append(id + "_" + usefulLife + "_" + quasiCarType + "_" + startTime + "_" + address + "_" + name + "_" + country + "_" + birthday + "_" + sex + "_" + firstTime);
            }
            catch
            {
                sb.Clear();
                sb.Append("识别错误");
            }
            return sb.ToString();
        }

        /// <summary>
        /// 行驶证识别
        /// </summary>
        /// <param name="imgPath"></param>
        /// <returns></returns>
        public static string VehicleLicense(string imgPath)
        {
            StringBuilder sb=new StringBuilder();
            try
            {
                var image = File.ReadAllBytes(imgPath);
                var result = client.VehicleLicense(image);
                JToken jk = result["result"];
                string model = jk["品牌型号"]["words"].ToString();
                string date = jk["发证日期"]["words"].ToString();
                string useType = jk["使用性质"]["words"].ToString();
                string engineNum = jk["发动机号码"]["words"].ToString();
                string register_date = jk["注册登记日期"]["words"].ToString();
                string carNum = jk["号牌号码"]["words"].ToString();
                string owner = jk["所有人"]["words"].ToString();
                string address = jk["住址"]["words"].ToString();
                string carId = jk["车辆识别代号"]["words"].ToString();
                string carType = jk["车辆类型"]["words"].ToString();
                sb.Append(model + "_" + date + "_" + useType + "_" + engineNum + "_" + register_date + "_" + carNum + "_" + owner + "_" + address + "_" + carId + "_" + carType);
            }
            catch
            {
                sb.Clear();
                sb.Append("识别错误");
            }


            return sb.ToString();
        }

        /// <summary>
        /// 车牌识别
        /// </summary>
        /// <param name="imgPath"></param>
        /// <returns></returns>
        public static string PlateLicense(string imgPath)
        {
            StringBuilder sb = new StringBuilder();
            try
            {
                var image = File.ReadAllBytes(imgPath);
                var result = client.PlateLicense(image);
                JToken jk = result["words_result"];
                string color = jk["color"].ToString();
                string num = jk["number"].ToString();
                sb.Append(color + "_" + num);
            }
            catch
            {
                sb.Clear();
                sb.Append("识别错误");
            }
            return sb.ToString();
        }

        public static string Receipt(string imgPath)
        {
            StringBuilder sb=new StringBuilder();
            var image = File.ReadAllBytes(imgPath);
            var options = new Dictionary<string, object>
            {
                {"recognize_granularity", "small"} // 定位单字符位置
            };
            var result = client.Receipt(image, options);
            return sb.ToString();
        }

        /// <summary>
        /// 营业执照识别
        /// </summary>
        /// <param name="imgPath"></param>
        /// <returns></returns>
        public static string BusinessLicense(string imgPath)
        {
            StringBuilder sb = new StringBuilder();
            var image = File.ReadAllBytes(imgPath);
            var result = client.BusinessLicense(image);
            return sb.ToString();
        }

        public static string FormBegin(string imgPath)
        {
            StringBuilder sb = new StringBuilder();
            var image = File.ReadAllBytes(imgPath);
            form.DebugLog = false; // 是否开启调试日志

            var result = form.BeginRecognition(image);
            return sb.ToString();
        }

        public static string FormGetResult()
        {
            StringBuilder sb = new StringBuilder();
            var options = new Dictionary<string, object>
            {
                {"result_type", "json"} // 或者为excel
            };
            var result = form.GetRecognitionResult("123344", options);
            return sb.ToString();
        }

        public static string FormToJson(string imgPath)
        {
            StringBuilder sb = new StringBuilder();
            var image = File.ReadAllBytes(imgPath);
            form.DebugLog = false; // 是否开启调试日志

            // 识别为Json
            var result = form.RecognizeToJson(image);
            return sb.ToString();
        }

        public static string FormToExcel(string imgPath)
        {
            StringBuilder sb = new StringBuilder();
            var image = File.ReadAllBytes(imgPath);
            form.DebugLog = false; // 是否开启调试日志

            // 识别为Excel
            var result = form.RecognizeToExcel(image);
            return sb.ToString();
        }
    }
}